#include "solar/trunk/NScrollLabel.h"


NScrollLabel::NScrollLabel(int step, QWidget *parent)
{
    setParent(parent);
    setAdvanceStep(step);
    IdlerWheel = new QTimer();
    IdlerWheel->setInterval(40);
    impact_bool.insert("text-overange-flag", false);
    impact_color["color"] = QColor(116,124,141);
    setAlignment(Qt::AlignCenter);
    setTextFormat(Qt::RichText);
    connect(IdlerWheel, &QTimer::timeout, this, &NScrollLabel::roundStep);
}

void NScrollLabel::resizeEvent(QResizeEvent *){
    setText(impact_str["text"]);
}

void NScrollLabel::setAdvanceStep(int step){
    impact_int["text-advance-step"] = step;
}

void NScrollLabel::setFont(QFont font){
    QLabel::setFont(font);
    setText(impact_str["text"]);
}

void NScrollLabel::setText(QString text){
    impact_str["text"] = text;
    QFontMetrics metrics(font());
    impact_int["text-lenght"] = metrics.horizontalAdvance(text);
    if (impact_int["text-lenght"] > width()){
        impact_bool["text-overange-flag"] = true;
        IdlerWheel->start();
    } else {
        impact_bool["text-overange-flag"] = false;
        IdlerWheel->stop();
    }
    setFixedHeight(font().pointSize() + 5);
    update();
}

void NScrollLabel::clear(){
    impact_str["text"].clear();
}

void NScrollLabel::setPenColor(QColor color){
    impact_color["color"] = color;
    update();
}

QString NScrollLabel::text(){
    return impact_str["text"];
}

void NScrollLabel::paintEvent(QPaintEvent *){
    QPainter impactpit(this);
    impactpit.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform);
    impactpit.setPen(Qt::NoPen);
    impactpit.setBrush(Qt::transparent);
    impactpit.drawRect(rect());
    impactpit.setPen(QPen(impact_color["color"]));
    impactpit.setFont(font());
    int centravy =  height() - (height() - font().pointSize()) / 2;
    int advancestep = impact_int["advance-step"];
    int metrics = impact_int["text-lenght"];
    int bestright = metrics + width() * 2;
    QString visibleText = impact_str["text"];
    if (impact_bool["text-overange-flag"]){
        impactpit.drawText(bestright - advancestep, centravy, visibleText);
        impactpit.drawText(-metrics + advancestep, centravy, visibleText);
    } else {
        int centrastart = (width() - metrics) / 2;
        impactpit.drawText(centrastart, centravy, visibleText);
    }
}

void NScrollLabel::roundStep(){
    int win_size_w = width();
    int fontmetrics = impact_int["text-lenght"];
    int advancestep = impact_int["text-advance-step"];
    impact_int["advance-step"] += advancestep;
    if (fontmetrics * 2 + win_size_w * 2 <= impact_int["advance-step"]) impact_int["advance-step"] = 0;
    update();
}
